import { defineStore } from 'pinia';
import { footprintAdminApi } from '@/api/footprints';
import { ElMessage } from 'element-plus';

export const useFootprintAdminStore = defineStore('footprintAdmin', {
  state: () => ({
    footprints: [],      // 当前页的足迹列表
    pagination: {        // 分页信息
      current_page: 1,
      per_page: 10,
      total_items: 0,
      total_pages: 0,
    },
    loading: false,      // 加载状态
  }),

  actions: {
    async fetchFootprints(params = { page: 1 }) {
      this.loading = true;
      try {
        const response = await footprintAdminApi.getFootprints(params);
        this.footprints = response.data.data.list;
        this.pagination = response.data.data.pagination;
      } catch (error) {
        console.error('获取足迹列表失败:', error);
        ElMessage.error('获取足迹列表失败');
      } finally {
        this.loading = false;
      }
    },

    async updateFootprint(payload) {
      try {
        const { property_id, ...data } = payload;
        await footprintAdminApi.updateFootprint(property_id, data);

        const index = this.footprints.findIndex(
          (fp) => fp.user_id === payload.user_id && fp.property_id === payload.property_id
        );
        if (index !== -1) {
          this.footprints[index].notes = payload.notes;
          this.footprints[index].rating = payload.rating;
        }
        return true;
      } catch (error) {
        console.error('更新足迹失败:', error);
        ElMessage.error(error.response?.data?.message || '更新足迹失败');
        return false;
      }
    },

    /**
     * 调用 footprintAdminApi 批量清空评价
     */
    async batchClearNotes(footprintsToClear) {
      this.loading = true;
      try {
        await footprintAdminApi.batchClearNotes(footprintsToClear);
        await this.fetchFootprints({ page: this.pagination.current_page });
        return true;
      } catch (error) {
        console.error('批量清空评价失败:', error);
        ElMessage.error(error.response?.data?.message || '批量操作失败');
        return false;
      } finally {
        this.loading = false;
      }
    },

     async deleteFootprint(payload) {
    try {
      await footprintAdminApi.deleteFootprint(payload.user_id, payload.property_id);

      // 从本地状态数组中移除被删除的项
      const index = this.footprints.findIndex(
        fp => fp.user_id === payload.user_id && fp.property_id === payload.property_id
      );
      if (index !== -1) {
        this.footprints.splice(index, 1);
      }

      // 更新分页总数
      if(this.pagination.total_items > 0) {
        this.pagination.total_items--;
      }

      return true; // 表示成功
    } catch (error) {
      console.error('删除足迹失败:', error);
      ElMessage.error(error.response?.data?.message || '删除足迹失败');
      return false; // 表示失败
    }
  },
  },
});